<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/22 0022
 * Time: ÉÏÎç 10:18
 */

namespace App\Http\Controllers\Xcx;


use App\Craftsman;
use App\Exceptions\CreateException;
use App\Extend\Tools;
use App\Http\Controllers\Controller;
use App\Item;
use App\Member;
use App\Project;
use App\Needwork;
use Carbon\Carbon;
use App\Xm_history;
use App\Gc_history;
use App\Xm_register;
use Illuminate\Http\Request;

/**
 * @property Craftsman model
 */
class   CraftsmanController extends Controller
{
    public function __construct(Craftsman $model)
    {
        $this->model = $model;
    }

    public function read($id,Request $request){
        $data = [];
        $item = $this->model->with('items')->with('teams')->with('header')->with('project')->with('members')->findOrFail($id);
        $data['avatar'] = $item->header->images[0];
        $data['name'] = $item->header->name;
        $data['origin'] = $item->header->origin??' ';
        $data['nation'] = $item->header->nation;
        $data['men'] = $item->mens;
        $data['skill'] = $item->teams->name;
        $data['time'] = date('Y-m-d',strtotime($item->updated_at));
        $data['city'] = $item->header->hope_city;
        $project = [];
        foreach ($item->items as $value){
            $tmp = [];
            $tmp['name'] = $value->name;
            $tmp['begin_at'] = $value->begin_at;
            $tmp['overed_at'] = $value->overed_at;
            array_push($project,$tmp);
        }
        //²é¿´°à×éµÄÀúÊ·¼ÇÂ¼
        $n = Gc_history::where('xm_id',$id)->where('id',auth('xcx')->user()->id)->first();
        if($n == null){
            if(auth('xcx')->user()->type == 2) { //ÅÐ¶Ïµ±Ç°ÊÇÏîÄ¿µÇÂ¼µÄ
                $xm_history = new Gc_history;
                $xm_history -> xm_id = $id; //½«´«¹ýÀ´µÄ°à×éid±£´æ½øÀúÊ·±íÖÐ
                $xm_history -> id = auth('xcx')->user()->id;//½«µ±Ç°ÊÇË­²é¿´µÄÀúÊ·¼ÇÂ¼´æÈë±íÖÐ£¬ÒÔ±ãÓÚÇø±ðÀúÊ·¼ÇÂ¼
                $xm_history -> save();
            }
        }
        //½áÊø
        $data['project'] = $project;
        return $this->success($data);
        
    }
    // public function work()
    // {
    //     $data = Needwork::
    // }
    public function index(Request $request)
    {
        $page = $request->get('page',1);
        $size = $request->get('size',10);
        $model = $this->model;
        $type = $request->input('type',0); //工种
        $province = $request->input('province',0);//省
        $city = $request->input('city',0); //市
        $addr = $request->input('area',0); //区
        if ($project = $request->get('team',0)!= 0){
            $model = $model->where('project_id',$project);
        }
        $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->get()->toArray();
        if($type != '' && $type != 0){      //如果当前工种不为空
        $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->where('project_id',$type)->get()->toArray();
        }
        if($province != 0 ){               //如果当前省不为空
            $res = \DB::table('members')->where('province',$province)->get();
            $a = [];
            foreach ($res as $k=>$v) {
                $a[] = $v->craftmans;
            }
            if($type != '' && $type  != 0){ //如果当前工种不为空
                 $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->where('project_id',$type)->get()->toArray();
            }else{
                $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->get()->toArray();
            }
        }
        if($province != 0 && $city != 0) { //如果当前省 市不为空
            $res = \DB::table('members')->where('province',$province)->where('city',$city)->get();
            $a = [];
             foreach ($res as $k=>$v) {
                     $a[] = $v->craftmans;
            }
            // dd($a);
            if($type != '' && $type  != 0){ 
            $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->where('project_id',$type)->get()->toArray();
            }else{
            $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->get()->toArray();
            }
        }
         if($province != 0 && $city != 0 && $addr != 0) { //如果当前省市区不为空
            $res = \DB::table('members')->where('province',$province)->where('city',$city)->where('area',$addr)->get();
            $a = [];
            foreach ($res as $k=>$v) {
                     $a[] = $v->craftmans;
            }
            if($type != '' && $type  != 0){
            $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->where('team_id',$type)->get()->toArray();
            }else{
                 $data = $model->with('header')->with('project')->limit($size)->offset(($page-1)*$size)->whereIn('id',$a)->get()->toArray();
            }
        }
        $list = [];
        foreach ($data as $value){
            $tmp = [];
            $tmp['name'] = $value['name'];
            $tmp['auth'] = $value['auth'];
            $tmp['number'] = $value['mens'];
            $tmp['city'] = $value['header']['hope_city'];
            $tmp['time']  = date('Y-m-d',strtotime($value['updated_at']));
            $tmp['images'] = $value['images'][0];
            $tmp['id'] = $value['id'];
            $tmp['nation'] = $value['header']['nation']??'ºº';
            $tmp['team'] = $value['project']['name'];
            array_push($list,$tmp);
        }
        return $this->success(compact('list'));
    }
    public function project() //½«ËùÓÐÉóºË¹ýµÄÏîÄ¿±éÀú³öÀ´
    {
        $data = Xm_register::where('shenhe',4)->get();
        $list = [];
        foreach ($data as $value) {
            $tmp=[];
            $tmp['id'] = $value['id'];
            $tmp['iconPath']="/images/icon/xian.png";
            $tmp['latitude']=floatval($value['longitude']);
            $tmp['longitude']=floatval($value['latitude']);
            $tmp['width']=24;
            $tmp['height']=30;
            $tmp['callout']=[];
            $tmp['callout']['content']="ÏîÄ¿¸ºÔðÈËÐÕÃû£º".$value['x_name']."\nÏîÄ¿¸ºÔðÈËµç»°:".$value['phone'];
            $tmp['callout']['color']='#FFFFFF';
            $tmp['callout']['borderRadius']=10;
            $tmp['callout']['bgColor']='#000000';
            $tmp['callout']['fontSize']=16;
            $tmp['callout']['padding']=10;
            array_push($list,$tmp);
        }
        return $this->success($list);
    }
    public function projectinfo(Request $request,$id) //ÐèÒªµ±Ç°µã»÷µÄÏîÄ¿id
    {
        $data = Xm_register::find($id);
        $n = Gc_history::where('xm_id',$id)->first();
        if($n == null) {
            if(auth('xcx')->user()->type == 1) { //ÅÐ¶Ïµ±Ç°ÊÇ°à×éÔÚ²é¿´ÏîÄ¿
                $gc_history = new Gc_history;
                $gc_history -> xm_id = $id; //½«µ±Ç°ÏîÄ¿µÄid ´æÈëÀúÊ·±íÖÐ
                $gc_history -> id = auth('xcx')->user()->id; //½«µ±Ç°ÊÇÄÄ¸ö°à×é²é¿´µÄÏîÄ¿ÀúÊ·¼ÇÂ¼´æÈë±íÖÐ£¬ÒÔ±ãÓÚÇø·Ö
                $gc_history -> save();
            }
        }
        return $this->success($data); //½«µ±Ç°ÏîÄ¿µÄÊý¾Ý·ÖÅä¹ýÈ¥
    }
    public function works(Request $request)
    {
        $size = $request -> input('size',10);
        $page = $request -> input('page',1);
        $data = Needwork::select('money','sum','times','addr','id')->where('shenhe','=','4')->limit($size)->offset(($page-1)*$size)->get();
        $arr = [];
        foreach ($data as $k=>$v) {
            $arr[$k]['title'] = $v->addr.'ÕÐ'.$v->work;
            $arr[$k]['money'] = $v->money;
            $arr[$k]['men'] = $v->sum;
            $arr[$k]['time'] = $v->times;
            $arr[$k]['address'] = $v->addr;
            $arr[$k]['id'] = $v->id;
        }
        // ->limit($size)->offset(($page-1)*$size)->get();
        return $this->success($arr);
    }
    public function workinfo(Request $request,$id)
    {

        $data = Needwork::find($id);
        $arr = [];
            $arr['title'] = $data->addr.'ÕÐ'.$data->work;
            $arr['money'] = $data->money;
            $arr['men'] = $data->sum;
            $arr['time'] = $data->times;
            $arr['desc'] = $data->desc;
            $arr['address'] = $data->addr;
            $arr['id'] = $data->id;
            $arr['lianxiren'] = auth('xcx')->user()->name;
            $arr['phone'] = Tools::getMaskPhone($data['phone']);
        $n = Xm_history::where('g_id',$id)->first();
        if($n == null) {
                $xm_history = new Xm_history;
                $xm_history -> g_id = $id;
                $xm_history -> id = auth('xcx')->user()->id;
                $xm_history -> save();
        }
        return $this->success($arr);
    }
    public function map()
    {
        /*
         {
            iconPath: "/images/icon/30-Point.png",
            id: 0,
            latitude:22.55331,
            longitude: 113.88300,
            width: 15,
            height: 20,
            callout:{
                content:"ÐÕ       Ãû£ºÄã²Â°¡\n°à×éÈËÊý:65ÈË",
                color:"#FFFFFF",
                borderRadius:10,
                bgColor:"#000",
                fontSize:16,
                padding:10
            }
         }
         *
         */
//        $data = $this->model->get()->each(function ($item){
//            if ($item->id>13){
//                $tmp = $item->lng;
//                $item->lng = $item->lat;
//                $item->lat =  $tmp;
//                $item->save();
//            }
//        });
        $data = $this->model->get();
        $list = [];
        foreach ($data as $value){
            $tmp = [];
            $tmp['id']  = $value['id'];
            if ($value['work']==1){
                $tmp['iconPath']="/images/icon/mang.png";
            }else{
                $tmp['iconPath']="/images/icon/xian.png";
            }
            $tmp['latitude']=floatval($value['lat']);
            $tmp['longitude']=floatval($value['lng']);
            $tmp['width']=24;
            $tmp['height']=30;
            $tmp['callout']=[];
            $tmp['callout']['content']="ÐÕ      Ãû£º".$value['name']."\n°à×éÈËÊý:".$value['mens']."ÈË";
            $tmp['callout']['color']='#FFFFFF';
            $tmp['callout']['borderRadius']=10;
            $tmp['callout']['bgColor']='#000000';
            $tmp['callout']['fontSize']=16;
            $tmp['callout']['padding']=10;
            array_push($list,$tmp);
        }
        return $this->success(compact('list'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws CreateException
     */
    public function store(Request $request)
    {
        if(auth('xcx')->user()->type == 1){
            $item = $request->only('project');
            $data = $request->only(['name','men','types','lng','lat','type','avatar']);
            $insertData = [
                'name'=>$data['name'],
                'mens'=>$data['men'],
                'team_id'=>$data['types'],
                'lng'=>$data['lng'],
                'lat'=>$data['lat'],
                'level'=>2,
                'project_id'=>$data['type'],
                'images'=>[
                    [
                        'name'=>$data['avatar']
                    ]
                ]
            ];
            $header = $request->only(['region','holp','name','lng','lat','card','phone','avatar']);
            $headerData = [
                'city'=>$header['region'],
                'hope_city'=>$header['holp'],
                'name'=>$header['name'],
                'lng'=>$header['lng'],
                'lat'=>$header['lat'],
                'card'=>$header['card']??'',
                'phone'=>$header['phone'],
                'headman_images'=>[
                    [
                        'name'=>$header['avatar']
                    ]
                ]
            ];

            if ($res = (new \App\Logic\Craftsman())->insertCraftsman($insertData,$headerData)){
                $craftmans_id = $res['res'];
                $member =$res['header'];
                $members = Member::findOrFail($member);
                $members->hope_city_province = $headerData['hope_city'][0]['code'];
                $members->hope_city_city = $headerData['hope_city'][0]['code'];
                $members->hope_city_area = $headerData['hope_city'][0]['code'];
                $members->save();
                $project = [];
                foreach ($item['project'] as $value){
                    $tmp = [];
                    $tmp['craftmans_id'] = $craftmans_id;
                    $tmp['name'] = $value['name'];
                    $tmp['begin_at'] = $value['start'];
                    $tmp['overed_at'] = $value['end'];
                    $tmp['city_name'] = $value['city'];
                    array_push($project,$tmp);
                }
                (new Item())->inssertAll($project);
                $user = auth('xcx')->user();
                $user->members_id = $member;
                $user->save();
                return $this->success();
            }
        }
        throw new CreateException();
    }

    public function info()
    {

        $user = auth('xcx')->user();
        $member = Member::with('craftsman')->findOrFail($user->members_id);
        $projects = Item::whereCraftmansId($member->craftsman->id)->get();
        $data = [];
//        dd($member);
        //region holp count name type men project avatar phone types
        $data['holp'] = Tools::genCode($member->hope_city_province,$member->hope_city_city,$member->hope_city_area);
        $data['region'] = Tools::genCode($member->province,$member->city,$member->area);
//        $tmp['count'] =
        $data['type'] = $member->craftsman->project_id;
        $data['men'] = $member->craftsman->mens;
        $data['avatar'] = $member->images[0];
        $data['phone'] = $member->phone;
        $data['types'] = $member->craftsman->team_id;
        $data['name'] = $member->name;
        $data['member_id'] = $member->id;
        $data['craftsman_id'] = $member->craftsman->id;
        $project = [];
        $count = 0;
        foreach ($projects as $value){
            $tmp = [];
            $tmp['name'] = $value['name'];
            $tmp['start'] = $value['begin_at'];
            $tmp['end'] = $value['overed_at'];
            $tmp['city'] = $value['city_name'];
            $count++;
            array_push($project,$tmp);
        }
        $data['count'] = $count;
        $data['project'] = $project;
        return $this->success($data);
    }

    public function update(Request $request)
    {
        $item = $request->only('project');
        $data = $request->only(['name','men','types','lng','lat','type','avatar','craftsman_id']);
        $insertData = [
            'name'=>$data['name'],
            'mens'=>$data['men'],
            'team_id'=>$data['types'],
            'lng'=>$data['lng'],
            'lat'=>$data['lat'],
            'level'=>2,
            'project_id'=>$data['type'],
            'images'=>[
                [
                    'name'=>$data['avatar']
                ]
            ],
            'id'=>$data['craftsman_id']
        ];
        $header = $request->only(['region','holp','name','lng','lat','card','phone','avatar','member_id']);
        $headerData = [
            'city'=>$header['region'],
            'hope_city'=>$header['holp'],
            'name'=>$header['name'],
            'lng'=>$header['lng'],
            'lat'=>$header['lat'],
            'card'=>$header['card']??'',
            'phone'=>$header['phone'],
            'headman_images'=>[
                [
                    'name'=>$header['avatar']
                ]
            ],
            'id'=>$header['member_id']
        ];

        if ($res = (new \App\Logic\Craftsman())->update($insertData,$headerData)){
            $craftmans_id = $res['res'];
            $member =$res['header'];
            $members = Member::findOrFail($member);
            $members->hope_city_province = $headerData['hope_city'][0]['code'];
            $members->hope_city_city = $headerData['hope_city'][0]['code'];
            $members->hope_city_area = $headerData['hope_city'][0]['code'];
            $members->save();
            $project = [];
            Item::destroy($craftmans_id);
            foreach ($item['project'] as $value){
                $tmp = [];
                $tmp['craftmans_id'] = $craftmans_id;
                $tmp['name'] = $value['name'];
                $tmp['begin_at'] = $value['start'];
                $tmp['overed_at'] = $value['end'];
                $tmp['city_name'] = $value['city'];
                array_push($project,$tmp);
            }
            (new Item())->inssertAll($project);
            $user = auth('xcx')->user();
            $user->members_id = $member;
            $user->save();
            return $this->success();
        }
        throw new CreateException();
    }
}